import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:easy_video/internal/api/video_api.dart';
import 'package:easy_video/model/video_model.dart';

class SearchController extends GetxController {
  late String keyword;

  List<VideoModel> list = [];

  int current_page = 0;

  bool loadDone = false;

  TextEditingController searchInputController = TextEditingController();

  @override
  void onInit() {
    super.onInit();
    this.keyword = Get.arguments["keyword"] ?? "";
    searchInputController.text = this.keyword;
    this.resetGet();
  }

  resetGet() {
    this.loadDone = false;
    this.current_page = 0;
    this.list.clear();
    this.getList();
  }

  search() async {
    this.keyword = this.searchInputController.text;
    this.resetGet();
  }

  getList() async {
    if (this.loadDone) {
      return;
    }
    VideoApi()
        .index(
      title: this.keyword,
      page: this.current_page,
    )
        .then(
      (response) {
        for (var item in response.data["data"]["data"]) {
          this.list.add(VideoModel.fromJson(item));
        }
        if (response.data["data"]["last_page"] > this.current_page) {
          this.current_page++;
        } else {
          this.loadDone = true;
        }
        this.update();
      },
    );
  }
}
